<template>
  <div class="dashboard-container">
    <div class="search">
      <el-row>
        <el-col :span="6">
          <div>
            <el-date-picker
              v-model="date"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
              @change="getStoreOrderAmount"
            />
          </div>
        </el-col>
        <el-col :span="18">
          <div style="float:right">
            <el-button @click="totalExport">导出</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <div>
      <el-table
        :data="storeData"
        border
        style="width: 100%"
        show-summary
      >
        <el-table-column
          fixed
          prop="store"
          label="门店"
          width="150"
        />
        <el-table-column
          prop="amount"
          label="营收总额"
          width="100"
        />
        <el-table-column
          prop="orderSettlePlatform"
          label="平台手续费"
          width="100"
        />
        <el-table-column
          label="手续费费率"
          width="100"
        >
          <template slot-scope="scope">
            {{ scope.row.settleRate }}%
          </template>
        </el-table-column>
        <el-table-column
          prop="deposit"
          label="pos机入金"
          width="100"
        />
        <el-table-column
          prop="depositFee"
          label="入金手续费"
          width="100"
        />
        <el-table-column
          label="入金费率"
          width="100"
        >
          <template slot-scope="scope">
            {{ scope.row.depositRate }}%
          </template>
        </el-table-column>
        <el-table-column
          prop="totalRevenue"
          label="平台营收"
          width="100"
        />
        <el-table-column
          prop="commission"
          label="支付手续费"
          width="100"
        />
        <el-table-column
          prop="margin"
          label="毛利"
          width="100"
        />
        <el-table-column
          label="毛利率"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.marginRate }}%</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="marketingPeople"
          label="营销人员"
        />
        <el-table-column
          prop="marketingPrice"
          label="营销费用"
        />
        <el-table-column
          label="营销费率"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.marketingRate*100 }}%</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="keyPersonal"
          label="关键人"
        />
        <el-table-column
          prop="keyPersonalPrice"
          label="关键人返点"
        />
        <el-table-column
          label="关键人费率"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.keyPersonalExpenses*100 }}%</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="documentary"
          label="跟单"
        />
        <el-table-column
          prop="documentaryPrice"
          label="跟单提成"
        />
        <el-table-column
          label="跟单费率"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.documentaryExpenses*100 }}%</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="netProfit"
          label="纯利"
        />
        <el-table-column
          label="纯利率"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.netProfitRate }}%</div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-divider>其他收入</el-divider>
    <div>
      <el-table
        :data="otherTransactions"
        width="50%"
      >
        <el-table-column
          prop="typeName"
          label="收入类型"
          width="200px"
        />
        <el-table-column
          prop="amount"
          label="金额"
          width="100px"
        />
      </el-table>
    </div>
  </div>
</template>

<script>
import exportExcelCsv from '@/utils/exportExcelCsv'
export default {
  data() {
    return {
      TYPE: {
        'deposit': '门店入金',
        'burn': '提现成功',
        'burn-to-destroy': '申请提现',
        'collect': '代收',
        'salary': '工资发放',
        'upload': '导入发放',
        'transfer': '转账',
        'deposit-fee': '手续费',
        'rollback': '回滚',
        'administrator': '管理员调整',
        'bond': '保证金',
        'bond-return': '退还保证金',
        'order-settle': '订单分账',
        'order-settle-agent': '酒代分成',
        'order-settle-place-manager': '管理员分成',
        'order-settle-platform': '平台分成',
        'order-settle-in-charge': '负责人分成',
        'order-settle-place': '场所分成',
        'order-settle-company': '资源公司分成',
        'order-settle-leader': '队长分成',
        'order-settle-broker': '经纪人分成',
        'order-settle-royalties': '提成',
        'order-settle-subsidy': '补贴',
        'order-settle-salary': '工资',
        'order-settle-booking': '订台分成',
        'order-settle-waiter': '服务员分成',
        'order-settle-store': '剩余余额',
        'order-settle-platform-fee': '平台手续费',
        'salary-settle': '工资分成',
        'salary-settle-staff': '员工工资',
        'salary-settle-leader': '队长工资分成',
        'salary-settle-broker': '经纪人工资分成',
        'onboard-fee': '入职费用',
        'faceid-authority-fee': '人脸核身费用',
        'insurance-fee': '保险费用',
        'blackhole-fee': '报销费用',
        'penalty-fee': '扣罚',
        'withdraw-fee': '提现手续费'
      },
      statistics: {
        actualEarns: '0.00',
        counterBalance: '0.00',
        earns: '0.00',
        settledAmount: '0.00',
        unSettledAmount: '0.00',
        orderAmount: '0.00', // 订单总金额
        depositAmount: '0.00', // pos机&第三方入金总金额
        storeProfit: '0.00', // 门店利润金额
        withdrawAmount: '0.00', // 提现总金额
        companyAmount: '0.00', // 资源公司(劳务)总金额
        transactionFee: '0.00', // 交易手续费
        depositFee: '0.00', // 入金手续费
        salaryAmount: '0.00', // 日薪总金额
        marginAmount: '0.00' // 保证金总金额
      },
      storeData: [],
      date: '',
      otherTransactions: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  created() {
    const now = new Date() // 当前时间
    const year = now.getFullYear() // 当前年份
    const month = now.getMonth() // 上个月
    const pevMonth = new Date(now.getFullYear(), now.getMonth() - 1)
    const startDate = `${pevMonth.getFullYear()}/${pevMonth.getMonth() + 1}/01 08:00:00` // 拼接成yyyy-mm-dd格式

    const endDate = `${year}/${month + 1}/01 08:00:00`
    this.date = [(new Date(startDate)).getTime(), (new Date(endDate)).getTime()]
    this.getStoreOrderAmount()
  },
  methods: {
    getStoreOrderAmount() {
      console.log(this.date)
      let startDate = new Date(this.date[0])
      let endDate = new Date(this.date[1])
      startDate = `${startDate.getFullYear()}/${startDate.getMonth() + 1}/${startDate.getDate()} ${startDate.getHours()}:${startDate.getMinutes()}:${startDate.getSeconds()}`
      endDate = `${endDate.getFullYear()}/${endDate.getMonth() + 1}/${endDate.getDate()} ${endDate.getHours()}:${endDate.getMinutes()}:${endDate.getSeconds()}`
      console.log(startDate, endDate)
      // 先查所有有效的store
      this.axios.get(`/manage/stores`, { params: { '@filter': `entity.getStatus() == 0 && entity.getId() > 4` }}).then((res) => {
        console.log('stores', res.data)
        const stores = res.data
        this.axios.get(`/manage/orders`, { params: {
          '@filter': `entity.getPaidTime() >= datetime.get('${startDate}') && entity.getPaidTime() <= datetime.get('${endDate}') && entity.getStatus() >= 2 && entity.getLaterPay() == 0 `,
          '@select': `SUM(entity.totalPrice) as amount, entity.store.name as store, entity.store.id as storeId, entity.store.user.id as userId, entity.store.config as config`,
          '@groupBy': 'entity.store.id',
          '@order': 'entity.store.id'
        }}).then((orderData) => {
          console.log('orderData', orderData)
          // 需要进行判断，是否有所有的营业门店，没有的，要手动加,否则只用pos的会不存在
          const storeIds = []
          for (const i of orderData.data) {
            // 撇开测试门店
            if (i.storeId > 4) {
              storeIds.push(i.storeId)
            }
          }
          for (const i of stores) {
            if (storeIds.indexOf(i.id) === -1) {
              orderData.data.push({
                amount: 0,
                store: i.name,
                storeId: i.id,
                userId: i.user.id,
                config: i.config
              })
            }
          }
          // 查stores对应的user下面的所有deposit
          let userFilter = ''
          let transactionFilter = ''
          let otherTransactionFilter = ''
          for (const i in orderData.data) {
            if (i == 0) {
              userFilter = `( entity.getUser().getId() == ${orderData.data[i].userId}`
              transactionFilter = `( entity.getFrom().getId() == ${orderData.data[i].userId}`
              otherTransactionFilter = `entity.getFrom().getId() != ${orderData.data[i].userId}`
            } else {
              userFilter += ` || entity.getUser().getId() == ${orderData.data[i].userId}`
              transactionFilter += ` || entity.getFrom().getId() == ${orderData.data[i].userId}`
              otherTransactionFilter += ` && entity.getFrom().getId() != ${orderData.data[i].userId}`
            } 
          }
          userFilter += ' )'
          transactionFilter += ' )'
          this.axios.get(`/manage/deposits`, {
            params: {
              '@filter': `entity.getCreatedTime() >= datetime.get('${startDate}') && entity.getCreatedTime() <= datetime.get('${endDate}') && entity.getStatus() == 1 && ${userFilter}`,
              '@select': `SUM(entity.amount) as amount, entity.user.id as userId, entity.user.username as user`,
              '@groupBy': 'entity.user.id'
            }
          }).then((depositData) => {
            console.log('deposit', depositData)
            // 查其他的入金数据
            this.axios.get(`/manage/transactions`, { params: {
              '@filter': `entity.getCreatedTime() >= datetime.get('${startDate}') && entity.getCreatedTime() <= datetime.get('${endDate}') && entity.getTo().getId() == 105 && ${otherTransactionFilter} && entity.getType() != "administrator"`,
              '@select': `SUM(entity.amount) as amount, entity.type as type`,
              '@groupBy': 'entity.type'
            }}).then((res) => {
              console.log('other', res)
              for (const i of res.data) {
                i['typeName'] = this.TYPE[i.type]
              }
              // 上面是不包含门店的酒水费用，门店酒水费用直接就是门店发过来的，type是administrator的
              this.axios.get(`/manage/transactions`, { params: {
                '@filter': `entity.getCreatedTime() >= datetime.get('${startDate}') && entity.getCreatedTime() <= datetime.get('${endDate}') && entity.getTo().getId() == 105 && entity.getType() == 'administrator'`,
                '@select': `SUM(entity.amount) as amount, entity.type as type`,
                '@groupBy': 'entity.type'
              }}).then((administrator) => {
                console.log('administrator',administrator.data)
                res.data.push({
                  type: 'administrator',
                  typeName: '管理员调整',
                  amount: administrator.data[0].amount
                })
                this.otherTransactions = res.data
              })
            })
            // 再查门店到平台账号的transaction
            this.axios.get(`/manage/transactions`, { params: {
              '@filter': `entity.getCreatedTime() >= datetime.get('${startDate}') && entity.getCreatedTime() <= datetime.get('${endDate}') && entity.getTo().getId() == 105 && ${transactionFilter}`,
              '@select': `SUM(entity.amount) as amount, entity.from.username as user, entity.type as type, entity.from.id as userId`,
              '@groupBy': 'entity.from.id, entity.type'
            }}).then((transactionData) => {
              console.log('transactionFilter', transactionData)
              const storeData = orderData.data
              for (const i in storeData) {
                storeData[i]['deposit'] = 0
                storeData[i]['depositFee'] = 0
                storeData[i]['orderSettlePlatform'] = 0
                for (const j of depositData.data) {
                  if (storeData[i].userId == j.userId) {
                    storeData[i]['deposit'] = j.amount
                  }
                }
                for (const t of transactionData.data) {
                  if (storeData[i].userId == t.userId) {
                    if (t.type == 'deposit-fee') {
                      // 入金手续费
                      storeData[i]['depositFee'] += parseFloat(t.amount)
                    } else if (t.type == 'order-settle-platform') {
                      // 订单的平台费用
                      storeData[i]['orderSettlePlatform'] += parseFloat(t.amount)
                    }
                  }
                }
              }
              for (const i in storeData) {
                // if (parseInt(storeData[i].amount) === 0 && parseInt(storeData[i].deposit) === 0) {
                //   storeData.splice(i, 1)
                // } else {
                // 分账手续费费率
                storeData[i]['settleRate'] = ((parseFloat(storeData[i].orderSettlePlatform) / parseFloat(storeData[i].amount)) * 100).toFixed(2)
                // 入金手续费费率
                if (parseFloat(storeData[i].deposit) === 0.00) {
                  storeData[i]['depositRate'] = 0
                } else {
                  storeData[i]['depositRate'] = ((parseFloat(storeData[i].depositFee) / parseFloat(storeData[i].deposit)) * 100).toFixed(2)
                }
                // 平台总营收
                storeData[i]['totalRevenue'] = (parseFloat(storeData[i].depositFee) + parseFloat(storeData[i].orderSettlePlatform)).toFixed(2)
                // 支付手续费
                storeData[i]['commission'] = ((parseFloat(storeData[i].amount) + parseFloat(storeData[i].deposit)) * 0.0025).toFixed(2)
                // 毛利
                storeData[i]['margin'] = (storeData[i]['totalRevenue'] - storeData[i]['commission']).toFixed(2)
                // 毛利率
                storeData[i]['marginRate'] = (storeData[i]['margin'] / (parseFloat(storeData[i].amount) + parseFloat(storeData[i].deposit)) * 100).toFixed(2)
                // 营销费率
                if (storeData[i].config != null && typeof (storeData[i].config.marketingExpenses) !== 'undefined') {
                  storeData[i]['marketingRate'] = storeData[i].config.marketingExpenses
                } else {
                  storeData[i]['marketingRate'] = 0
                }
                // 营销人员
                if (storeData[i].config != null && typeof (storeData[i].config.marketingPeople) !== 'undefined') {
                  storeData[i]['marketingPeople'] = storeData[i].config.marketingPeople
                } else {
                  storeData[i]['marketingPeople'] = '无'
                }
                // 营销费用 = 毛利 * 营销费率
                storeData[i]['marketingPrice'] = (storeData[i]['margin'] * parseFloat(storeData[i]['marketingRate'])).toFixed(2)

                // 关键人费率
                if (storeData[i].config != null && typeof (storeData[i].config.keyPersonalExpenses) !== 'undefined') {
                  storeData[i]['keyPersonalExpenses'] = storeData[i].config.keyPersonalExpenses
                } else {
                  storeData[i]['keyPersonalExpenses'] = 0
                }
                // 关键人
                if (storeData[i].config != null && typeof (storeData[i].config.keyPersonal) !== 'undefined') {
                  storeData[i]['keyPersonal'] = storeData[i].config.keyPersonal
                } else {
                  storeData[i]['keyPersonal'] = '无'
                }
                // 关键人返点
                storeData[i]['keyPersonalPrice'] = (storeData[i]['margin'] * parseFloat(storeData[i]['keyPersonalExpenses'])).toFixed(2)

                // 跟单提成比例
                if (storeData[i].config != null && typeof (storeData[i].config.documentaryExpenses) !== 'undefined') {
                  storeData[i]['documentaryExpenses'] = storeData[i].config.documentaryExpenses
                } else {
                  storeData[i]['documentaryExpenses'] = 0
                }
                // 跟单
                if (storeData[i].config != null && typeof (storeData[i].config.documentary) !== 'undefined') {
                  storeData[i]['documentary'] = storeData[i].config.documentary
                } else {
                  storeData[i]['documentary'] = '无'
                }
                // 跟单提成
                storeData[i]['documentaryPrice'] = (storeData[i]['margin'] * parseFloat(storeData[i]['documentaryExpenses'])).toFixed(2)

                // 纯利  = 毛利 - 营销费用
                storeData[i]['netProfit'] = (storeData[i]['margin'] - storeData[i]['marketingPrice'] - storeData[i]['documentaryPrice'] - storeData[i]['keyPersonalPrice']).toFixed(2)
                // 纯利率
                storeData[i]['netProfitRate'] = (storeData[i]['netProfit'] / (parseFloat(storeData[i].amount) + parseFloat(storeData[i].deposit)) * 100).toFixed(2)
                // }
              }
              const realData = []
              for (const i of storeData) {
                if (i.totalRevenue > 0 && i.storeId > 4) {
                  realData.push(i)
                }
              }
              this.storeData = realData
              console.log('storeData', storeData)
            })
          })
        })
      })
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ' 元'
        } else {
          sums[index] = 'N/A'
        }
      })
      return sums
    },
    totalExport() {
      // table数据
      const list = JSON.parse(JSON.stringify(this.storeData))
      const otherTransactions = JSON.parse(JSON.stringify(this.otherTransactions))
      if (list.length === 0) {
        this.$message.error('暂无导出数据')
        return
      }
      const otherLabel = {
        'typeName': '类型',
        'amount': '总价'
      }
      const label = {
        'store': '门店',
        'amount': '总营销',
        'orderSettlePlatform': '平台手续费',
        'settleRate': '手续费费率',
        'deposit': 'pos机入金',
        'depositFee': '入金手续费',
        'depositRate': '入金手费率',
        'totalRevenue': '平台营收',
        'commission': '支付手续费',
        'margin': '毛利',
        'marginRate': '毛利率',
        'marketingPeople': '营销人员',
        'marketingPrice': '营销费用',
        'marketingRate': '营销费率',
        'keyPersonal': '关键人',
        'keyPersonalPrice': '关键人返点',
        'keyPersonalExpenses': '关键人费率',
        'documentary': '跟单',
        'documentaryExpenses': '跟单提成',
        'documentaryPrice': '跟单费率',
        'netProfit': '纯利',
        'netProfitRate': '纯利率'
      }
      let startDate = new Date(this.date[0])
      let endDate = new Date(this.date[1])
      startDate = `${startDate.getFullYear()}年${startDate.getMonth() + 1}月${startDate.getDate()}日${startDate.getHours()}时${startDate.getMinutes()}分${startDate.getSeconds()}秒`
      endDate = `${endDate.getFullYear()}年${endDate.getMonth() + 1}月${endDate.getDate()}日${endDate.getHours()}时${endDate.getMinutes()}分${endDate.getSeconds()}秒`
      exportExcelCsv(label, list, `${startDate}到${endDate}场所收入月报表.csv`)
      exportExcelCsv(otherLabel, otherTransactions, `${startDate}到${endDate}平台其他收入月报表.csv`)
    }
  }
}
</script>

<style lang="scss" scoped>
.search{
  padding:10px;
}

.deposit{
  padding: 20px 0px;
  margin: 5px 10px;
  background-color: #2979ff;
  color: #fff;
  font-size:24px;
  border-radius: 5px;
  text-align: center;
}
</style>
